var util = require('../../utils/util.js')
const db = wx.cloud.database()
Page({
  data: {
    imgList: [],
    newsInfo: {istop: 0},
    userInfo: {}
  },
  
  onShow:function()
  {
    var userInfo = wx.getStorageSync('userInfo');
    if (userInfo == "") {
      wx.navigateTo({
        url: '../auth/auth'
      })
    } else {
      this.setData({
        userInfo: userInfo
      })
    }
  },

  switchChange: function(e) {
    let newsInfo = this.data.newsInfo
    if (e.detail.value == true) {
      newsInfo.istop = 1
    } else {
      newsInfo.istop = 0
    }
    this.setData({
      newsInfo: newsInfo
    })
  },

  updateValue: function(event) {
    let name = event.currentTarget.dataset.name;
    let newsInfo = this.data.newsInfo
    newsInfo[name] = event.detail.value
    this.setData({
      newsInfo: newsInfo
    })
  },

  ChooseImage() {
    wx.chooseImage({
      count: 3, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        wx.showLoading({
          title: '图片上传中...',
        })
        var time = util.formatTimestring(new Date());
        var FilePaths = []
        const temFilePaths = res.tempFilePaths
        let promiseArr = [];
        for (let i = 0; i < temFilePaths.length; i++) {
          let promise = new Promise((resolve, reject) => {
            var randstring = Math.floor(Math.random() * 1000000).toString() + '.png'
            randstring = time + '-' + randstring
            wx.cloud.uploadFile({
              cloudPath: 'newsImages/' + randstring,
              filePath: temFilePaths[i], // 文件路径
              success: res => {
                // get resource ID
                console.log(res.fileID)
                FilePaths[i] = res.fileID
                resolve(res);
              },
              fail: err => {
                reject(error);
              }
            })
          })
          promiseArr.push(promise)
        }

        Promise.all(promiseArr).then((result) => {
          if (this.data.imgList.length != 0) {
            this.setData({
              imgList: this.data.imgList.concat(FilePaths)
            })
          } else {
            this.setData({
              imgList: FilePaths
            })
          }
          wx.hideLoading()
        })
      }
    });
  },

  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },

  DelImg: function(event) {
    console.log(event.currentTarget.dataset.id)
    var id = event.currentTarget.dataset.id
    var imgList = this.data.imgList
    wx.cloud.deleteFile({
      fileList: [imgList[id]]
    }).then(res => {
      imgList.splice(id, 1)
      this.setData({
        imgList: imgList
      })
      console.log(res.fileList)
    }).catch(error => {
      // handle error
    })
  },

  submitform: function(event) {
    let newsInfo = this.data.newsInfo
    let userInfo = this.data.userInfo
    db.collection('news').add({
        // data 字段表示需新增的 JSON 数据
        data: {
          title: newsInfo.title,
          content: newsInfo.content,
          publisher: userInfo.nickName,
          imgUrl: this.data.imgList,
          avatarUrl: userInfo.avatarUrl,
          submitdate: db.serverDate(),
          istop: newsInfo.istop,
          comment: 0,
          appreciate: 0,
          view: 0
        }
      })
      .then(res => {
        wx.reLaunch({
          url: '../home/home'
        })
      })
  },

})